package com.hjy.wechatdevelopermode.util;

import com.google.common.base.Charsets;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.MessageFormat;


/**
 * @CopyRight: 版权所有
 * @Author: hejinyi
 * @Description:
 * @Date: 2020/5/25
 */
@Component
public class AccessTokenUtil {
    private static final Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);

//    @Autowired
//    private RedisService redisService;
//    /**
//     * 获取微信AccessToken
//     * @return
//     */
//    public String getAccessToken(String wxAppid,String appsecret){
//
//        logger.info("==========》getWeiAccessToken:Entering,param is [{}]",wxAppid);
//
//        String accessToken = redisService.getCache(RedisKeyConstant.WEIXIN_ACCESS_TOKEN + "_" + wxAppid);
//
//        if(StringUtils.isEmpty(accessToken)){
//            setWeixinToken(wxAppid,appsecret);
//            accessToken = redisService.getCache(RedisKeyConstant.WEIXIN_ACCESS_TOKEN + "_" + wxAppid);
//        }
//        logger.debug("==========》getWeiAccessToken:End,result is [{}]",accessToken);
//
//        return accessToken;
//    }
//
//    private void setWeixinToken(String wxappid,String appsecret){
//        CloseableHttpClient client=null;
//        CloseableHttpResponse response=null;
//        try {
//
//            String tokenUrl= MessageFormat.format(WeiXinParamesUtil.tokenUrl,wxappid,appsecret);
//            logger.info("==========》setWeixinToken:accessToken requset url is [{}]",tokenUrl);
//
//            client= HttpClients.createDefault();
//            HttpGet get=new HttpGet(tokenUrl);
//            response=client.execute(get);
//            if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
//                HttpEntity entity=response.getEntity();
//                String content= EntityUtils.toString(entity, Charsets.UTF_8);
//                logger.info("==========》setWeixinToken:accessToken is [{}]",content);
//
//                JsonObject jsonObject=new JsonParser().parse(content).getAsJsonObject();
//
//                String token = jsonObject.get("access_token").getAsString();
//                redisService.setCache(RedisKeyConstant.WEIXIN_ACCESS_TOKEN+"_"+wxappid,token,ACCESS_TOKEN_EXPIRY_TIME);
//
//                //请求jsticket
//                String url=MessageFormat.format(DFProperties.jsapiticket_url,token);
//                logger.info("==========》setWeixinToken:jsticket url is [{}]",url);
//                get=new HttpGet(url);
//                response=client.execute(get);
//                if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
//                    content=EntityUtils.toString(response.getEntity(),Charsets.UTF_8);
//                    logger.info("==========》setWeixinToken:accessToken parse reslut is [{}]",content);
//                    JsonObject ticketObject=new JsonParser().parse(content).getAsJsonObject();
//                    String jsapiTicket =ticketObject.get("ticket").getAsString();
//                    redisService.setCache(RedisKeyConstant.WEIXIN_JSAPI_TICKET+"_"+wxappid,jsapiTicket,ACCESS_TOKEN_EXPIRY_TIME);
//                }
//            }
//        }
//
//        catch (ClientProtocolException e) {
//            logger.error("client请求错误",e);
//        } catch (IOException e) {
//            logger.error("client请求错误",e);
//        }finally {
//            if (client!=null){
//                try {
//                    client.close();
//                } catch (IOException e) {
//                    logger.error("client关闭错误",e);
//                }
//            }
//        }
//    }


    public String getAccessToken(String wxAppid,String appsecret){
        CloseableHttpClient client=null;
        CloseableHttpResponse response=null;
        try {
            String tokenUrl= MessageFormat.format(WeiXinParamesUtil.tokenUrl,wxAppid,appsecret);
            logger.info("==========》setWeixinToken:accessToken requset url is [{}]",tokenUrl);

            client= HttpClients.createDefault();
            HttpGet get=new HttpGet(tokenUrl);
            response=client.execute(get);
            if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity, Charsets.UTF_8);
                logger.info("==========》setWeixinToken:accessToken is [{}]", content);

                JsonObject jsonObject = new JsonParser().parse(content).getAsJsonObject();

                String token = jsonObject.get("access_token").getAsString();

                return token;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
